<?php
namespace Api\Controller;
use Think\Controller;
class QuanController extends CommonController {
	public function index(){
        if ($_GET['pageNum']) {
            $page = max(1,intval(I('pageNum')));
            $page = (int)$page * 10 -1;
        } else {
            $page = 0;
        }
		$map['tp_quan.wid'] = session('wid');
        if(!empty($_GET['topic'])){
            $map['tp_quan.topic'] = $_GET['topic'];
        }
        if($_GET['tabindex'] == 1){
            $openid_list = M('quan_addfriend')->where(array('from_openid'=>$_GET['openid']))->getField('add_openid',true);

            $openid_list = implode(',',$openid_list);
            if(empty($openid_list)){
                $list = array();
                $this->ajaxReturn($list);
            }
            $map['tp_quan.openid'] = array('in',$openid_list);
        }
    
        if(I('t')=='bottom'){
            //上拉
            $list = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')
                ->where($map)
                ->field("tp_quan.*, tp_member.nickname,tp_member.user_age,tp_member.gender, tp_member.headimgurl, tp_member.openid as follow_openid")
                ->order("last_time desc")
                ->limit( 0,$_GET['pageNum'] *20 )
                ->select();
        }else{
            //下拉
            $list = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')
                ->where($map)
                ->field("tp_quan.*, tp_member.nickname,tp_member.user_age,tp_member.gender, tp_member.headimgurl, tp_member.openid as follow_openid")
                ->order("create_time desc,last_time desc")
                ->limit( 0,20)
                ->select();
        }
        $wechat = M('wechat')->where(['wid'=>session("wid")])->find();

        foreach ($list as $key => $value) {
            //查圈子信息
            if($value['type'] == 2){
                $list[$key]['circle'] = M('circle')->where(['id'=>$value['circleid']])->find();
            }

            $list[$key]['pics'] = explode(',', $value['pics']);
            $eq['tp_quan_reply.wid'] = session('wid');
            $eq['tp_quan_reply.qid'] = $value['id'];
            $list[$key]['reply_list'] = M("QuanReply")->join('tp_member ON tp_quan_reply.openid = tp_member.openid')->where($eq)->field("tp_quan_reply.*, tp_member.nickname, tp_member.headimgurl")->order('create_time DESC')->limit(5)->select();
            $eq1['qid'] = $value['id'];
            $eq1['openid'] = $_GET['openid'];
            $list[$key]['is_zan'] = M("QuanZanLog")->where($eq1)->find();
            $list[$key]['isquan'] = 1;
            $flag = array();

            //骗审开关是否打开，隐藏评论等
            if($wechat['pian'] == 1){
                $list[$key]['pian'] = 1;
            }else{
                $list[$key]['pian'] = 0;
            }

            foreach($list[$key]['reply_list'] as $v){
                $flag[] = $v['create_time'];
            }
            array_multisort($flag, SORT_ASC, $list[$key]['reply_list']);
        }
        //帮助了多少人
        foreach ($list as $key => $value) {
            //问答帮助
            if ($value['type'] == 1) {
                $listAll = [];
                $listHelp = [];
                //回复
                $listR = M('quan_reply')->field('openid')->where(['qid' => $value['id']])->group('openid')->select();
                foreach ($listR as $k => $v) {
                    $listAll[] = $v['openid'];
                    $listHelp[] = $v['openid'];
                }
                //顶
//                $listD = M('quan_zan_log')->field('openid')->where(['qid' => $value['id']])->group('openid')->select();
//                foreach ($listD as $k => $v) {
//                    $listAll[] = $v['openid'];
//                    $listHelp[] = $v['openid'];
//                }
                //赞
//                $listZ = M('quan_zan_log')->alias('a')
//                    ->join('tp_quan_reply b on a.reply_id = b.id')
//                    ->where(['b.qid' => $value['id']])
//                    ->group('b.openid')
//                    ->select();
//                foreach ($listZ as $k => $v) {
//                    $listAll[] = $v['openid'];
//                }
                $openidArr = array_unique($listAll);
                $openidHelp = array_unique($listHelp);
                $list[$key]['help_num'] = count($openidHelp);
                $list[$key]['join_num'] = count($openidArr);
            } else { //其他帮助
                $listOtherZ = [];
                //点赞
//                $listZZ = M('quan_zan_log')->field('openid')->where(['qid' => $value['id']])->group('openid')->select();
//                foreach ($listZZ as $k => $v) {
//                    $listOtherZ[] = $v['openid'];
//                }
                //评论  问答
                $listRR = M('quan_reply')->field('openid')->where(['qid' => $value['id'], 'type' => 1])->group('openid')->select();
                foreach ($listRR as $k => $v) {
                    $listOtherZ[] = $v['openid'];
                }
                $listOtherChange = array_unique($listOtherZ);
                $list[$key]['help_num'] = count($listOtherChange);
            }
        }

        //顶部轮播图
        $arr['banner'] = M('adv')->where(['type'=>'quan','wid'=>session('wid')])->select();
        $this->ajaxReturn($list);
	}
    //话题动态
    public function topicIndex(){
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = (int)$page * 10;
        } else {
            $page = 0;
        }

        $map['tp_quan.wid'] = session('wid');
        if(!empty($_GET['topic'])){
            $map['tp_quan.topic'] = $_GET['topic'];
        }
        $wechat = M('wechat')->where(['wid'=>session('wid')])->find();
        //最新
        $list = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')
            ->where($map)
            ->field("tp_quan.*, tp_member.nickname,tp_member.user_age,tp_member.gender, tp_member.headimgurl, tp_member.openid as follow_openid")
            ->order("last_time desc")
            ->limit(0, $page)
            ->select();
        foreach ($list as $key => $value) {
            //查圈子信息
            if($value['type'] == 2){
                $list[$key]['circle'] = M('circle')->where(['id'=>$value['circleid']])->find();
            }
            //骗审
            if($wechat['pian'] == 1){
                $list[$key]['pian'] =1;
            }else{
                $list[$key]['pian'] =0;
            }

            $list[$key]['pics'] = explode(',', $value['pics']);
            $eq['tp_quan_reply.wid'] = session('wid');
            $eq['tp_quan_reply.qid'] = $value['id'];
            $list[$key]['reply_list'] = M("QuanReply")->join('tp_member ON tp_quan_reply.openid = tp_member.openid')->where($eq)->field("tp_quan_reply.*, tp_member.nickname, tp_member.headimgurl")->limit(5)->select();
            $eq1['qid'] = $value['id'];
            $eq1['openid'] = $_GET['openid'];
            $list[$key]['is_zan'] = M("QuanZanLog")->where($eq1)->find();
            $list[$key]['isquan'] = 1;
        }
        //最赞
        $list2 = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')
            ->where($map)
            ->field("tp_quan.*, tp_member.nickname, tp_member.headimgurl, tp_member.openid as follow_openid,tp_member.gender,tp_member.user_age")
            ->order("zan_num desc")
            ->limit(0, $page)
            ->select();
        foreach ($list2 as $key => $value) {
            //查圈子信息
            if($value['type'] == 2){
                $list2[$key]['circle'] = M('circle')->where(['id'=>$value['circleid']])->find();
            }

            $list2[$key]['pics'] = explode(',', $value['pics']);
            $eq['tp_quan_reply.wid'] = session('wid');
            $eq['tp_quan_reply.qid'] = $value['id'];
            $list2[$key]['reply_list'] = M("QuanReply")->join('tp_member ON tp_quan_reply.openid = tp_member.openid')->where($eq)->field("tp_quan_reply.*, tp_member.nickname, tp_member.headimgurl,tp_member.gender,tp_member.user_age")->limit(5)->select();
            $eq1['qid'] = $value['id'];
            $eq1['openid'] = $_GET['openid'];
            $list2[$key]['is_zan'] = M("QuanZanLog")->where($eq1)->find();
            $list2[$key]['isquan'] = 1;
        }
        $arr['new_list'] = $list;
        $arr['zan_list'] = $list2;
        $this->ajaxReturn($arr);
    }
    //话题详情
    public function topic(){
        $map['tp_quan.wid'] = session('wid');
        if(!empty($_GET['topic'])){
            $map['tp_quan.topic'] = $_GET['topic'];
        }
        $count = M("Quan")->where($map)->group('openid')->count();//参与数量
        $where['wid'] = session('wid');
        $where['topic'] = ['like','%'.$_GET['topic'].'%'];
        $count2 = M("Quan")->where($where)->count();//动态数
        //发起者
        $member = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')
            ->where($map)
            ->field("tp_member.*,tp_quan.pics")
            ->order("create_time asc")
            ->limit(0, 1)
            ->find();
        foreach($member as $k=>$v){
            if(strpos($v['pics'],",")) {
                $pics = explode(',', $v['pics']);
                $member[$k]['pics'] = $pics[0];
            }else{
                $member[$k]['pics'] =$v['pics'];
            }
        }
        //活跃榜
        $sql = "SELECT count(*) as c,q.openid,m.nickname,m.headimgurl from tp_quan q left join
                    tp_member m on m.openid =q.openid
                    where q.wid = ". session('wid') ."
                    and mid <> {$member['mid']}
                    and topic = '".$_GET['topic']."'
                     GROUP BY openid ORDER BY c  desc
                    limit 0,3";
        $user = M()->query($sql);
        $arr['user'] = $user?$user:0;//活跃榜
        $arr['member'] = $member;//发起者
        $arr['join_count'] = $count;//参与数量
        $arr['news_count'] = $count2;//动态数
        $arr['w_count'] = $count2 +$count +round(5,10);//围观数
        $this->ajaxReturn($arr);
    }
    public function banner()
    {
        //顶部轮播图
        $arr = M('adv')->where(['type'=>'quan','wid'=>session('wid')])->select();
        $this->ajaxReturn($arr);

    }
    // 获取新闻列表
    public function newsList(){
        $map['wid'] = session('wid');
        $list = M("News")->where($map)->order('last_time desc')->select();
        foreach ($list as $key => $value) {
            $list[$key]['pics'] = explode(',', $value['pics']);
        }
        $this->ajaxReturn($list);
    }
    //获取资讯分类列表
    public function cateList(){
        $map = array();
        $map['status'] = 1;
        $map['wid'] = session('wid');
        $list = M("news_cate")->where($map)->order('add_time desc')->select();
        $arr = array();
        $arr['name'] = '推荐';
        $arr['id'] = 0;
        array_unshift($list,$arr);
        $this->ajaxReturn($list);
    }
    //搜索资讯列表
    public function  selectNews(){
        $id = $_GET['id'];
        $map = array();
        if(!empty($id)){
            $map['cate_id'] = $id;
        }
        $map['wid'] = session('wid');
        $list = M('news')
            ->where($map)
            ->order("id DESC")
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['pics'] = explode(',', $value['pics']);
            $count = M('news_reply')
                ->where(array('nid'=>$value['id']))
                ->group('openid')
                ->count('id');
            if(empty($count)){
                $count = 0;
            }
            if(!empty($value['video_url'])){
                $url = $this->handleVideoUrl($value['video_url']);
                $list[$key]['video_url'] = $url;
            }
            $list[$key]['reply_num'] = $count;
            $list[$key]['add_time'] = $this->getAnnounceTime($value['create_time']);
        }
        $this->ajaxReturn($list);
    }
    //处理视频地址

    //搜索资讯列表
    public function  searchNews(){
        $key = $_GET['key'];
        $map = array();
        $map['title'] = array('like', "%".$key."%");
        $map['wid'] = session('wid');
        $list = M('news')
            ->where(array($map))
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['pics'] = explode(',', $value['pics']);
        }
        $this->ajaxReturn($list);
    }
    public function newsItem(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $list = M("News")->where($map)->find();
        if(!empty($list['video_url'])){
            $url = $this->handleVideoUrl($list['video_url']);
            $list['video_url'] = $url;
        }
        //广告商品
        if($list['goodsid']){
            $goods = M('goods')->where(['id'=>$list['goodsid']])->find();
            $list['goods'] = $goods;
        }
        if($list['zan_num'] > 0){
            $list['is_zan'] = true;
        }else{
            $list['is_zan'] = false;
        }
        $reply_list = M('news_reply')
            ->alias('n')
            ->join("tp_member m ON m.openid=n.openid","LEFT")
            ->field("n.*,m.nickname, m.headimgurl")
            ->where(array('nid'=>$_GET['id']))
            ->select();
        $list['reply_list'] = $reply_list;
        $this->ajaxReturn($list);
    }
    // 获取视频列表
    public function videoList(){
        $map['wid'] = session('wid');
        $map['status'] = 1;
        $map['start_date'] = array('egt', date("Y-m-d"));
        $list['zhibo_list'] = M("Zhibo")->where($map)->select();
        $eq['wid'] = session('wid');
        $eq1['wid'] = session('wid');
        foreach ($list['zhibo_list'] as $k => $v) {
            $eq['mid'] = $v['member_id'];
            $list['zhibo_list'][$k]['nickname'] = M("Member")->where($eq)->getField('nickname');

            $eq1['id'] = array('in', explode(',', $v['goods']));
            $eq1['type'] = '';
            $eq1['status'] = 1;
            $count = M("Goods")->where($eq1)->count();
            $goods_list = M("Goods")->where($eq1)->limit(3)->select();
            foreach ($goods_list as $key => $value) {
                $goods_list[$key]['pics'] = explode(',', $value['pics']);
            }
            $list['zhibo_list'][$k]['goods_list'] = $goods_list;
            $list['zhibo_list'][$k]['count'] = $count;
        }

        $map['video_path'] = array('neq', '');
        $list['video_list'] = M("Quan")->where($map)->select();

        $this->ajaxReturn($list);
    }
    public function getVideoList(){
        $page = $_GET['page'];
        $openid = $_GET['openid'];
        $map = array();
        $map['q.wid'] = session('wid');
        $map['status'] = 1;
        $map['video_path'] = array('neq', '');
        $list = M('Quan')
            ->alias('q')
            ->join('tp_member m ON m.openid=q.openid',"LEFT")
            ->where($map)
            ->limit($page*3,3)
            ->order('id DESC')
            ->field("q.*,m.nickname, m.headimgurl")
            ->select();
        foreach($list as $key=>$value){
            $list[$key]['is_zan'] = M('QuanZanLog')
                ->where(array('qid'=>$value['id'],'openid'=>$openid))
                ->getField('id');
        }
        $this->ajaxReturn($list);
    }
    // 获取礼物列表
    public function giftList(){
        $map['wid'] = session('wid');
        // $map['wid'] = 0;
        $list = M("QuanGift")->where($map)->select();
        $this->ajaxReturn($list);
    }
    // 生成礼物订单
    public function payGift(){
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $map['wid'] = session('wid');
        $map['id'] = $_POST['gift_id'];
        $info = M("QuanGift")->where($map)->find();
        if(!$info){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        $data['wid'] = session('wid');
        $data['type'] = $_POST['type'];
        $data['gift_id'] = $info['id'];
        $data['from'] = $_POST['from'];
        $data['to'] = $_POST['to'];
        $data['out_trade_no'] = $this->build_order_no();
        $data['title'] = $info['name'];
        $data['price'] = $info['price'];
        $data['pay_money'] = $info['price'];
        $data['status'] = 0;
        $data['is_pay'] = 0;
        $data['create_time'] = date("Y-m-d H:i:s");
        if(!$giftorder = M("QuanGiftOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"2网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/index",array('type'=>'gift'));
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("购买礼物");
        $input->SetAttach($data['title']);
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($data['pay_money']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['from']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        //积分产生
        $pro = M('credit_setint')->where(['wid' => session('wid')])->find();
        $credit = $data['pay_money'] * $pro['give_gift'];
        addCredit($_POST['from'], $credit, $giftorder, session('wid'), 5);

        echo $jsApiParameters;
    }
    // 获取热门话题列表
    public function topicList(){
        $map['wid'] = session('wid');
        $map['topic'] = array('neq', '');
        $list = M("Quan")->where($map)->group('topic')->order("create_time desc,last_time desc")->limit(0,3)->select();
        foreach ($list as $key => $value) {
            $list[$key]['pics'] = explode(',', $value['pics']);
        }
        $this->ajaxReturn($list);
    }
    // 获取达人榜
    public function darenList(){
        $map['tp_quan.wid'] = session('wid');
        if($_GET['type'] == 'today'){
            $map['tp_quan.last_time'] = array('between', array(date("Y-m-d H:i:s", strtotime("-1 days")), date("Y-m-d H:i:s")));
        }
        $list = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')->where($map)->
        field("tp_quan.*, tp_member.nickname, tp_member.headimgurl, sum(tp_quan.zan_num) as all_zan_num")
            ->group('tp_quan.openid')->order("all_zan_num desc")->select();
        foreach ($list as $key => $value) {
            //是否关注
            $follow = M('quan_follow')->where(['openid'=>I('openid'),'follow_openid'=> $value['openid']])->find();
            $list[$key]['is_follow'] =$follow?true:false;
            $list[$key]['pics'] = explode(',', $value['pics']);
            unset($follow);
        }
        $this->ajaxReturn($list);
    }

    public function member(){
        $map['wid'] = session('wid');
        $map['openid'] = $_GET['openid'];


        $info = M("Member")->where($map)->find();
        $info['me'] = M("Member")->where(['wid'=>session('wid'),'openid'=>I('mopenid')])->find();
        //是否关注
        $follow = M('quan_follow')->where(['openid'=>I('mopenid'),'follow_openid'=> $map['openid']])->find();
        $info['is_follow'] =$follow?true:false;

        $eq['follow_openid'] = $_GET['openid'];
        $info['follow_num'] = M("QuanFollow")->where($eq)->count();

        //暗恋个数
        $loveNum = M("quan_anlian")->where(['wid' => session('wid'), 'an_openid' => $_GET['openid'], 'state' => 1])->count();
        $info['love_num'] = $loveNum;

        $eq1['to'] = $_GET['openid'];
        $eq1['is_pay'] = 1;
        $info['gift_num'] = M("QuanGiftOrder")->where($eq1)->count();

        $eq2['tp_quan.openid'] = $_GET['openid'];
        $info['quan_list'] = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')->where($eq2)->field("tp_quan.*, tp_member.nickname, tp_member.user_age,tp_member.gender,tp_member.headimgurl, tp_member.openid as follow_openid")->order("last_time desc")->select();

        $info['pics'] = array();
        foreach ($info['quan_list'] as $key => $value) {
            $pics = explode(',', $value['pics']);
            $info['quan_list'][$key]['pics'] = $pics;
            foreach ($pics as $k => $v) {
                if(!empty($v)){
                   $info['pics'][] = $v; 
                }
            }
        }
        $info['circle'] = M("circle_member")->alias('cm')->field("c.*")->join("tp_circle c on c.id =cm.uid")->where(['cm.openid'=>$_GET['openid'],'cm.wid'=>session('wid')])->select();
        if($info['circle']){
            $info['has_circle'] = 1;
            foreach($info['circle'] as $k =>$v){
                $info['circle'][$k]['name']  = mb_substr($v['name'],0,3,'utf-8')."...";
            }
        }else{
            $info['has_circle'] = 0;
        }
        $this->ajaxReturn($info);
    }

	public function item(){
        $map['tp_quan.wid'] = session('wid');
        $map['tp_quan.id'] = $_GET['id'];
        $info = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')->where($map)->field("tp_quan.*, tp_member.nickname, tp_member.headimgurl, tp_member.openid as follow_openid")->find();
        $info['pics'] = explode(",", $info['pics']);

        $eq1['qid'] = $info['id'];
        $eq1['openid'] = $_GET['openid'];
        $info['is_zan'] = M("QuanZanLog")->where($eq1)->getField('id');
        $eq['tp_quan_reply.wid'] = session('wid');
        $eq['tp_quan_reply.qid'] = $_GET['id'];
        $info['reply_list'] = M("QuanReply")->join('tp_member ON tp_quan_reply.openid = tp_member.openid')->where($eq)->field("tp_quan_reply.*, tp_member.nickname, tp_member.headimgurl")->order('id DESC')->select();
        $info['reply_num'] = count($info['reply_list']);
        $eq2['follow_openid'] = $info['follow_openid'];
        $eq2['openid'] = $_GET['openid'];
        $info['is_follow'] = M("QuanFollow")->where($eq2)->getField('id');
        foreach ($info['reply_list'] as $key => $value) {
        	$info['reply_list'][$key]['num'] = $key+1;
        }
        $this->ajaxReturn($info);
    }

    public function itemRandom(){
        $map['tp_quan.wid'] = session('wid');
        if($_GET['id'] == 'undefined'){
            $map['video_path'] = array('neq','');
            $info = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')->where($map)->field("tp_quan.*, tp_member.nickname, tp_member.headimgurl, tp_member.openid as follow_openid")->order('id DESC')->find();
        }else{
            $map['video_path'] = array('neq','');
            $map['tp_quan.id'] = array('lt',$_GET['id']);
            $info = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')->where($map)->field("tp_quan.*, tp_member.nickname, tp_member.headimgurl, tp_member.openid as follow_openid")->order('id DESC')->find();
        }
        if(empty($info)){
            $info = array();
            $info['err'] = 2;
            $this->ajaxReturn($info);
        }
        $info['pics'] = explode(",", $info['pics']);

        $eq1['qid'] = $info['id'];
        $eq1['openid'] = $_GET['openid'];
        $info['is_zan'] = M("QuanZanLog")->where($eq1)->getField('id');
        $eq['tp_quan_reply.wid'] = session('wid');
        $eq['tp_quan_reply.qid'] = $_GET['id'];
        $info['reply_list'] = M("QuanReply")->join('tp_member ON tp_quan_reply.openid = tp_member.openid')->where($eq)->field("tp_quan_reply.*, tp_member.nickname, tp_member.headimgurl")->order('id DESC')->select();
        $info['reply_num'] = count($info['reply_list']);
        $eq2['follow_openid'] = $info['follow_openid'];
        $eq2['openid'] = $_GET['openid'];
        $info['is_follow'] = M("QuanFollow")->where($eq2)->getField('id');
        foreach ($info['reply_list'] as $key => $value) {
            $info['reply_list'][$key]['num'] = $key+1;
        }
        $this->ajaxReturn($info);

    }

	public function add(){
        $data['content'] = I("post.content");
        $data['pics'] = I("post.pics");
        $data['openid'] = I("post.openid");
        $data['video_path'] = I("post.video_path");
        $data['video_thumb'] = I("post.video_thumb");
        $data['wid'] = session('wid');
        $data['create_time'] = date("Y-m-d H:i:s");

        if(empty($data['content']) && empty($data['video_path']) && empty($data['pics'])){
        	$arr = array("err_code"=>400,"err_msg"=>"请填写发帖内容！");
            $this->ajaxReturn($arr);
        }
        if(empty($data['openid'])){
        	$arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

        if(substr($data['content'], 0, 1) == '#'){
            preg_match("/#(.*?)#/", $data['content'], $match);
            $data['topic'] = $match[1];
        }

        if($info_id = M("Quan")->where($map)->add($data)){
            $map['id'] = $info_id;
            $data['status'] = 1;
            M("Quan")->where($map)->save($data);
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

    }
    //加入圈子
    public function circle_follow(){
        $data['openid'] = I('openid');
        $data['uid'] = I('id');
        $data['wid'] =session('wid');
        $list = M('circle_member')->where($data)->find();
        if($list){
            $r = M('circle_member')->where($data)->delete();
        }else{
            $data['time'] =date("Y-m-d H:i:s",time());
            $r = M('circle_member')->add($data);
        }
        if($r){
            $arr = array("err_code"=>0,"err_msg"=>"操作成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }
    //发布圈子帖子
    public function circle_content(){
        $data['content'] = I("post.content");
        $data['pics'] = I("post.pics");
        $data['openid'] = I("post.openid");
        $data['video_path'] = I("post.video_path");
        $data['video_thumb'] = I("post.video_thumb");
        $data['wid'] = session('wid');
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['circleid'] = I('post.circleid');
        $data['type'] = 2; //0同城圈 1问答 2圈子内帖子
        if(empty($data['content']) && empty($data['video_path']) && empty($data['pics'])){
            $arr = array("err_code"=>400,"err_msg"=>"请填写发帖内容！");
            $this->ajaxReturn($arr);
        }
        if(empty($data['openid'])){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        if($info_id = M("Quan")->add($data)){
            $map['id'] = $info_id;
            $data['status'] = 1;
            M("Quan")->where($map)->save($data);
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }
    //我的圈子列表
    public function getnotice(){
        $openid = I('openid');
        $arr = M("circle_notice")->alias('n')->field('n.*,c.name,c.img_url')->join('tp_circle c on c.id =n.uid')->where(['c.wid'=>session('wid'),'c.openid'=>$openid])->select();
        $this->ajaxReturn($arr);
    }
    //删除公告
    public function delnotice(){
        $id = I('id');
        $r = M('circle_notice')->where(['id'=>$id])->delete();
        if($r){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }
    //添加圈子
    public function addnotice(){
        $name = trim(I('circle'));
        $notice = I('notice');
        if(!$name || $name == "undefined"){
            $arr = array("err_code"=>400,"err_msg"=>"请选择圈子");
            $this->ajaxReturn($arr);
        }
        if(!$notice || $notice == "undefined"){
            $arr = array("err_code"=>400,"err_msg"=>"请输入公告");
            $this->ajaxReturn($arr);
        }
        $circle = M('circle')->where(['wid'=>session('wid'),'name'=>$name])->find();
        $data['uid']= $circle['id'];
        $data['content'] = $notice;
        $data['wid'] = session('wid');
        $data['time'] = date('Y-m-d H:i:s',time());
        $r = M('circle_notice')->add($data);
        if($r){
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }
    //圈子公告
    public function notice(){
        $openid = I('openid');
        $arr = [];
        $list = M('circle')->where(['wid'=>session('wid'),'openid'=>$openid])->select();
        foreach($list as $k=>$v){
            $arr[$k] = $v['name'];
        }
        $this->ajaxReturn($arr);
    }
    //圈子详情
    public function circle_detail(){
        $eq['id'] = I('id');
        $arr['circle'] = M('circle')->where($eq)->find();
        $w['uid'] = I('id');
        $w['openid'] = I('openid');
        $arr['follow'] = M('circle_member')->where($w)->find()?1:0;
        //粉丝数
        $arr['mcount'] = M('circle_member')->where(['uid'=>I('id')])->count();
        //发帖数
        $arr['acount'] = M('quan')->where(['circleid'=>I('id'),'type'=>2])->count();
        //公告
        $arr['notice'] = M("circle_notice")->where(['uid'=>I('id')])->select();
        //动态
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = (int)$page * 10;
        } else {
            $page = 0;
        }
        $map['tp_quan.wid'] = session('wid');
        $map['tp_quan.type'] = 2;
        $map['tp_quan.circleid'] = $eq['id'];
        $list = M("Quan")->join('tp_member ON tp_quan.openid = tp_member.openid')->where($map)
            ->field("tp_quan.*, tp_member.nickname, tp_member.gender,tp_member.user_age,tp_member.headimgurl, tp_member.openid as follow_openid")
            ->order("last_time desc")
            ->limit(0, $page)
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['pics'] = explode(',', $value['pics']);

            $eq['tp_quan_reply.wid'] = session('wid');
            $eq['tp_quan_reply.qid'] = $value['id'];
            $list[$key]['reply_list'] = M("QuanReply")->join('tp_member ON tp_quan_reply.openid = tp_member.openid')->where($eq)->field("tp_quan_reply.*, tp_member.nickname, tp_member.headimgurl")->limit(5)->select();
            $eq1['qid'] = $value['id'];
            $eq1['openid'] = $_GET['openid'];
            $list[$key]['is_zan'] = M("QuanZanLog")->where($eq1)->find();
        }
        $arr['list'] = $list;
        //圈友
        $where['uid'] = I('id');
        $arr['member'] = M('circle_member')->alias('cm')->field("m.*")->join("tp_member m on m.openid = cm.openid","LEFT")->where($where)->select();
        //距离计算
        if (I('la') != 'undefined' && I('lo') != 'undefined') {
            foreach($arr['member'] as $ko=>$vo){
                if ($vo['latitude'] && $vo['longitude']) {
                    $earthRadius = 6367000;
                    $lat1 = (float) I('la');//纬度
                    $lng1 = (float) I('lo');//经度
                    $lat2 = (float) $vo['latitude'];
                    $lng2 = (float) $vo['longitude'];
                    $lat1=($lat1* pi()) / 180;
                    $lng1=($lng1* pi()) / 180;
                    $lat2=($lat2* pi()) / 180;
                    $lng2=($lng2* pi()) / 180;
                    $calcLongitude = $lng2-$lng1;
                    $calcLatitude = $lat2-$lat1;
                    $stepOne = pow(sin($calcLatitude/2),2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude/2),2);
                    $stepTwo = 2* asin(min(1, sqrt($stepOne)));
                    $distance = round($earthRadius*$stepTwo);
                    if ($distance < 1000) {
                        $arr['member'][$ko]['r_distance'] = $distance.'米';
                    } else {
                        $distance = $distance / 1000;
                        $arr['member'][$ko]['r_distance'] = round($distance, 2).'公里';
                    }
                } else {
                    $arr['member'][$ko]['r_distance'] = '';
                }
            }
        } else {
            $arr['member'][]['r_distance'] = '';
        }


        $this->ajaxReturn($arr);
    }
    //圈子列表
    public function circle(){
        $map['cm.wid'] = session('wid');
        $map['c.status'] = 0;
        $map['cm.openid'] = I('openid');
        $list['mine'] =M('circle_member')->alias('cm')->field("c.*")->join("tp_circle c on c.id = cm.uid","LEFT")->where($map)->select();
        $sql = "select c.* from tp_circle c where id not in
                (SELECT uid from tp_circle_member where openid ='".I('openid')."' and wid =".session('wid').")
                and status =0";
        $query = "select count(*) as count from tp_circle c where id not in
                (SELECT uid from tp_circle_member where openid ='".I('openid')."' and wid =".session('wid').")
                and status =0";
        $list['other'] =M()->query($sql);
        $count = M()->query($query);
        $list['count'] =$count[0]['count'];
        //我的圈子
        $this->ajaxReturn($list);
    }
    //添加圈子
    public function circleadd(){
        $data['remark'] = I("post.remark");
        $data['img_url'] = trim(I("post.pics"));
        $data['openid'] = I("post.openid");
        $data['wid'] = session('wid');
        $data['name'] = trim(I("post.name"));
        $data['createtime'] = date("Y-m-d H:i:s");

        if( empty($data['img_url']) || empty($data['remark']) || empty($data['name'])){
            $arr = array("err_code"=>400,"err_msg"=>"内容不全");
            $this->ajaxReturn($arr);
        }
        if(empty($data['openid'])){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        $cir = M('circle')->where(['name'=>$data['name']])->find();
        if($cir){
            $arr = array("err_code"=>400,"err_msg"=>"圈子已存在！");
            $this->ajaxReturn($arr);
        }
        if($info_id = M("circle")->add($data)){
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

    }

    public function reply(){
        $data['content'] = I("post.content");
        // $data['pics'] = I("post.pics");
        $data['openid'] = I("post.openid");
        $data['wid'] = session('wid');
        $data['qid'] = I("post.id");
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['reply_openid'] = I('post.reply_openid');
        $data['reply_nickname'] = I('post.reply_nickname');

        $map =array();
        $map['wid'] = session('wid');
        $map['qid'] = I('post.id');
        $map['content'] = I("post.content");
        $map['openid'] = I("post.openid");
        $info = M('QuanReply')->where($map)->find();

        if(!empty($info)){
            $arr = array("err_code"=>400,"err_msg"=>"不能评论相同内容！");
            $this->ajaxReturn($arr);
        }

        if(empty($data['content'])){
        	$arr = array("err_code"=>400,"err_msg"=>"请输入回帖内容！");
            $this->ajaxReturn($arr);
        }
        if(empty($data['openid'])){
        	$arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        $info_id = M("QuanReply")->add($data);
        if($info_id){
            $member = M('member')->where(array('openid'=>I('post.openid')))->find();
            //回复的视频
            if(I('reply_part') == 'video'){
                if($data['reply_openid']) {
                    //回复
                    sendReplyMessage($data['reply_openid'], 'video', session('wid'), $info_id);
                }else{
                    //评论
                    $news = M('quan')->where(['id'=>$data['qid']])->find();
                    if($news['openid'] != $data['openid']){
                        //如果是自己发布的不给发
                        sendReplyMessage($news['openid'],'video',session('wid'),$info_id);
                    }
                }
            }elseif(I('reply_part') == 'quan'){
                //评论
                $news = M('quan')->where(['id'=>$data['qid']])->find();
                if($data['reply_openid']) {
                    //回复
                    sendReplyMessage($data['reply_openid'], 'quan', session('wid'), $info_id);
                    if($news['openid'] != $data['reply_openid']){
                        //回复别人也给帖子人发
                        sendReplyMessage($news['openid'],'quan',session('wid'),$info_id);
                    }
                }else{
                    if($news['openid'] != $data['openid']){
                        //如果是自己发布的不给发
                        sendReplyMessage($news['openid'],'quan',session('wid'),$info_id);
                    }
                }
            }

            $data['headimgurl'] = $member['headimgurl'];
            $data['nickname'] = $member['nickname'];
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！",'data'=>$data);
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    public function favo(){
    	$map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        if(M("Quan")->where($map)->setInc('favo_num')){
        	$arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
        	$arr = array("err_code"=>400,"err_msg"=>"你已经关注过了！");
            $this->ajaxReturn($arr);
        }
    }

    // 点赞
    public function zan(){
    	$map['wid'] = session('wid');
        $map['id'] = $_GET['id'];

        $eq['qid'] = $_GET['id'];
        $eq['openid'] = $_GET['openid'];
        if(M("QuanZanLog")->where($eq)->find()){
            M("QuanZanLog")->where($eq)->delete();
            if(M("Quan")->where($map)->setDec('zan_num')){
                $arr = array("err_code"=>0, "err_msg"=>"-1");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
                $this->ajaxReturn($arr);
            }
        }else{
            M("QuanZanLog")->add($eq);
            if(M("Quan")->where($map)->setInc('zan_num')){
                $arr = array("err_code"=>0, "err_msg"=>"1");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
                $this->ajaxReturn($arr);
            }
        }
    }
    // 关注
    public function follow(){
        $model = M('QuanFollow');

        $eq['follow_openid'] = $_POST['follow_openid'];
        $eq['openid'] = $_POST['openid'];
        if($model->where($eq)->find()){
            if($model->where($eq)->delete()){
                $arr = array("err_code"=>0, "err_msg"=>"-1");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
                $this->ajaxReturn($arr);
            }
        }else{
            $eq['create_time'] = date("Y-m-d H:i:s");
            if($model->add($eq)){
                $arr = array("err_code"=>0, "err_msg"=>"1");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
                $this->ajaxReturn($arr);
            }
        }
    }
    public function news_zan(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];

        $eq['nid'] = $_GET['id'];
        $eq['openid'] = $_GET['openid'];
        if(M("NewsZanLog")->where($eq)->find()){
            M("NewsZanLog")->where($eq)->delete();
            if(M("News")->where($map)->setDec('zan_num')){
                $arr = array("err_code"=>0, "err_msg"=>"-1");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
                $this->ajaxReturn($arr);
            }
        }else{
            M("NewsZanLog")->add($eq);
            if(M("News")->where($map)->setInc('zan_num')){
                $arr = array("err_code"=>0, "err_msg"=>"1");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
                $this->ajaxReturn($arr);
            }
        }
    }
    public function news_reply(){
        $data['content'] = I("post.content");
        // $data['pics'] = I("post.pics");
        $data['openid'] = I("post.openid");
        $data['wid'] = session('wid');
        $data['nid'] = I("post.id");
        $data['reply_openid'] = I('post.reply_openid');
        $data['reply_nickname'] = I('post.reply_nickname');
        $data['create_time'] = date("Y-m-d H:i:s");

        if(empty($data['content'])){
            $arr = array("err_code"=>400,"err_msg"=>"请输入回帖内容！");
            $this->ajaxReturn($arr);
        }
        if(empty($data['openid'])){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        $info_id = M("NewsReply")->add($data);
        if($info_id){
            //有评论文章（需要判断是不是自己文章，自己文章不给发了）。有回复评论
            if($data['reply_openid']) {
                //回复评论
                sendReplyMessage($data['reply_openid'], 'news', session('wid'), $info_id);
                //资讯为后台添加 没有作者openid
                /*}else{
                    //评论文章
                    $news = M('news')->where(['id'=>$data['nid']])->find();
                    if($news['openid'] != $data['openid']){
                        //如果是自己文章不给发
                        sendReplyMessage($news['openid'],'news',session('wid'),$info_id);
                    }
                }*/
            }
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //
    public function addQuestion () {
        $data['wid'] = session('wid');
        $data['openid'] = I('openid');
        $data['title'] = I('title');
//        $data['reamrk'] = I('reamrk');
        $data['content'] = I('content');
        $data['pics'] = I('pics');
        $data['latitude'] = I('latitude');
        $data['longitude'] = I('longitude');
        $data['type'] = 1;
        if(!I('title')){
            $arr = array("err_code"=>400,"err_msg"=>"标题不能为空！");
            $this->ajaxReturn($arr);
        }
        if(!I('content')){
            $arr = array("err_code"=>400,"err_msg"=>"请输入问题描述！");
            $this->ajaxReturn($arr);
        }
        if(!I('pics')){
            $arr = array("err_code"=>400,"err_msg"=>"请上传图片！");
            $this->ajaxReturn($arr);
        }
        $row = M('quan')->add($data);
        if ($row) {
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        } else {
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    public function getAllQuestion () {
        $where['wid'] = session('wid');
        $where['type'] = 1;
        $list = M('quan')->where($where)->order('last_time desc')->select();

        foreach ($list as $key => $value) {
            $listAll = [];
            $manList = [];
            //回复
            $listR = M('quan_reply')->field('openid')->where(['qid' => $value['id']])->group('openid')->select();
            foreach ($listR as $k => $v) {
                $listAll[] = $v['openid'];
            }
            //顶
            $listD = M('quan_zan_log')->field('openid')->where(['qid' => $value['id']])->group('openid')->select();
            foreach ($listD as $k => $v) {
                $listAll[] = $v['openid'];
            }
            //赞
            $listZ = M('quan_zan_log')->alias('a')
                ->join('tp_quan_reply b on a.reply_id = b.id')
                ->where(['b.qid' => $value['id']])
                ->group('b.openid')
                ->select();
            foreach ($listZ as $k => $v) {
                $listAll[] = $v['openid'];
            }

            $openidArr = array_unique($listAll);
            foreach ($openidArr as $k => $v) {
                $member = M('member')->where(['openid' => $v])->find();
                $manList[] = $member;
            }
            if (count($manList) > 5) {
                for ($i=0; $i<5; $i++) {
                    $manListLimit[] = $manList[$i];
                }
                $list[$key]['canList'] = $manListLimit;
            } else {
                $list[$key]['canList'] = $manList;
            }
            $list[$key]['dingNum'] = count($listD);
            $list[$key]['canNum'] = count($manList);
        }

        $this->ajaxReturn($list);
    }

    public function getQuestion () {
        //$where['wid'] = session('wid');
        //$where['type'] = 1;
        $where['a.id'] = I('id');
        $list = M('quan')->alias('a')
                         ->field('a.*, b.nickname, b.headimgurl, b.gender, b.user_age')
                         ->join('tp_member b on a.openid = b.openid')
                         ->where($where)
                         ->find();
        $this->ajaxReturn($list);
    }

    public function addReply () {
        print_r($_POST);
        $data['wid'] = session('wid');
        $data['qid'] = $_POST['qid'];
        $data['openid'] = $_POST['openid'];
        $data['content'] = $_POST['content'];
        $data['create_time'] = date('Y-m-d H:i:s', time());
        $data['type'] = 1;
        $row = M('quan_reply')->add($data);
        $row ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
    }

    public function addReplySon () {
        print_r($_POST);
        $data['wid'] = session('wid');
        $data['qid'] = $_POST['qid'];
        $data['pid'] = $_POST['pid'];
        $data['openid'] = $_POST['openid'];
        $data['content'] = $_POST['content'];
        $data['create_time'] = date('Y-m-d H:i:s', time());
        $data['type'] = 1;
        $row = M('quan_reply')->add($data);
        if($row){
            //评论
            $reply = M('quan_reply')->where(['id'=>$data['pid']])->find();
            sendReplyMessage($reply['openid'],'question',session('wid'),$row);
            $this->ajaxReturn(1);
        }else{

            $this->ajaxReturn(0);
        }

    }

    public function getZanItem () {
        $data['wid'] = session('wid');
        $data['qid'] = I('qid');
        $data['openid'] = I('openid');
        $data['type'] = '1';//问答点赞
        $row = M('quan_zan_log')->where($data)->find();
        $row ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
    }

    public function changeDing () {
        $data['wid'] = session('wid');
        $data['qid'] = I('qid');
        $data['openid'] = I('openid');
        $data['type'] = '1';//问答点赞
        if (I('ding')) {
            $row = M('quan_zan_log')->where($data)->delete();
            $row ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        } else {
            $row = M('quan_zan_log')->add($data);
            $row ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        }
    }

    public function getQuestionsReply () {
        $where['tp_quan_reply.qid'] = I('qid');
        $where['tp_quan_reply.type'] = '1';
        $where['tp_quan_reply.pid'] = 0;

        $list = M("quan_reply")
                    ->join('tp_member ON tp_quan_reply.openid = tp_member.openid')
                    ->where($where)
                    ->field("tp_quan_reply.*, tp_member.nickname, tp_member.headimgurl, tp_member.openid as follow_openid, tp_member.gender, tp_member.user_age")
                    ->order("is_caina desc, last_time desc")
                    ->select();

        foreach ($list as $key => $value) {
            $whereHelp['wid'] = session('wid');
            $whereHelp['qid'] = ['neq', 0];
            $whereHelp['openid'] = $value['openid'];
            $whereHelp['type'] = '1';

            $helpNum = M('quan_reply')->where($whereHelp)->group('qid')->count();
            $list[$key]['helpNum'] = $helpNum;

            $eq['tp_quan_reply.type'] = '1';
            $eq['tp_quan_reply.pid'] = $value['id'];

            $list[$key]['reply_list'] = M("QuanReply")->join('tp_member ON tp_quan_reply.openid = tp_member.openid')->where($eq)->field("tp_quan_reply.*, tp_member.nickname, tp_member.headimgurl")->order('last_time desc')->limit(50)->select();

            //$eq1['qid'] = I('qid');
            $eq1['openid'] = I('openid');
            $eq1['type'] = '1';
            $eq1['reply_id'] = $value['id'];

            $list[$key]['is_zan'] = M("QuanZanLog")->where($eq1)->find();

            $eq2['type'] = '1';
            $eq2['reply_id'] = $value['id'];
            $list[$key]['zan_num'] = M("QuanZanLog")->where($eq2)->count();
        }
        $this->ajaxReturn($list);
    }

    // 回复点赞
    public function anwerZan () {
        $map['reply_id'] = $_GET['id'];// reply_id
        $map['type'] = '1';
        $map['openid'] = $_GET['openid'];
        $map['qid'] = 0;

        if(M("QuanZanLog")->where($map)->find()){
            if(M("QuanZanLog")->where($map)->delete()){
                $arr = array("err_code"=>0, "err_msg"=>"-1");
                $this->ajaxReturn($arr);
            } else {
                $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
                $this->ajaxReturn($arr);
            }
        }else{
            if(M("QuanZanLog")->add($map)){
                $arr = array("err_code"=>0, "err_msg"=>"1");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
                $this->ajaxReturn($arr);
            }
        }
    }

    //参与总人数
    public function getJoinMans () {
        $listAll = [];
        $manList = [];
        //回复
        $listR = M('quan_reply')->field('openid')->where(['qid' => $_GET['qid']])->group('openid')->select();
        foreach ($listR as $k => $v) {
            $listAll[] = $v['openid'];
        }
        //顶
        $listD = M('quan_zan_log')->field('openid')->where(['qid' => $_GET['qid']])->group('openid')->select();
        foreach ($listD as $k => $v) {
            $listAll[] = $v['openid'];
        }
        //赞
        $listZ = M('quan_zan_log')->alias('a')
                                  ->join('tp_quan_reply b on a.reply_id = b.id')
                                  ->where(['b.qid' => $_GET['qid']])
                                  ->group('b.openid')
                                  ->select();
        foreach ($listZ as $k => $v) {
            $listAll[] = $v['openid'];
        }

        $openidArr = array_unique($listAll);
        foreach ($openidArr as $k => $v) {
            $member = M('member')->where(['openid' => $v])->find();
            $manList[] = $member;
        }
        if (count($manList) > 5) {
            for ($i=0; $i<5; $i++) {
                $manListLimit[] = $manList[$i];
            }
            $manLists['list'] = $manListLimit;
        } else {
            $manLists['list'] = $manList;
        }
        $manLists['dingNum'] = count($listD);
        $manLists['num'] = count($manList);
        $this->ajaxReturn($manLists);
    }

    //
    public function changeCaiNa () {
        $id = $_GET['id'];
        $arr = M('quan_reply')->where(['id' => $id])->find();
        if ($arr) {
            $is_caina = $arr['is_caina'];
            if ($is_caina) {
                $row = M('quan_reply')->where(['id' => $id])->save(['is_caina' => 0]);
                $this->ajaxReturn($row);
            } else {
                $row = M('quan_reply')->where(['id' => $id])->save(['is_caina' => 1]);
                $this->ajaxReturn($row);
            }
        } else {
            $this->ajaxReturn(0);
        }
    }

    //访问量
    public function increaseVisitNum () {
        $openid = I('openid');
        $arr = M('member')->field('visit_num')->where(['openid' => $openid, 'wid' => session('wid')])->find();
        if ($arr) {
            $num = $arr['visit_num'] + 1;
            M('member')->where(['openid' => $openid, 'wid' => session('wid')])->save(['visit_num' => $num]);
        }
    }

    //
    public function isAnlian () {
        $an_openid = I('openid');
        $from_openid = I('myopenid');
        $where['wid'] = session('wid');
        $where['an_openid'] = $an_openid;
        $where['from_openid'] = $from_openid;
        $row = M('quan_anlian')->where($where)->find();
        if ($row) {
            $row['state'] ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        }
        $this->ajaxReturn(0);
    }

    public function changeAnlian () {
        $an_openid = I('openid');
        $from_openid = I('myopenid');
        $where['wid'] = session('wid');
        $where['an_openid'] = $an_openid;
        $where['from_openid'] = $from_openid;
        $state = I('state');
        $row = M('quan_anlian')->where($where)->find();
        if ($row) {
            $suc = M('quan_anlian')->where($where)->save(['state' => $state]);
            $suc ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        } else {
            $suc = M('quan_anlian')->add(['state' => $state, 'an_openid' => $an_openid, 'from_openid' => $from_openid, 'wid' => session('wid')]);
            $suc ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        }
    }
    //附近
    public function fujin()
    {
        $wid = session('wid');
        $lat = I('la');
        $lng = I('lo');
        $where=" WHERE wid=".$wid;
        $where .= " and openid != '".I('openid')."' ";
        $pageindex = max(1,intval(I('page')));
        $pagesize = 10;
        $sql="SELECT *, ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-latitude*PI()/180)/2),2)+COS($lat*PI()/180)*COS(latitude*PI()/180)*POW(SIN(($lng*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli
     FROM tp_member".$where ." ORDER BY juli ASC";
        $select_sql =$sql." LIMIT " .($pageindex - 1) * $pagesize.",".$pagesize;
        $result = M()->query($select_sql);
        foreach($result as $k=>$v){
            //是否关注
            $follow = M('quan_follow')->where(['openid'=>I('openid'),'follow_openid'=> $v['openid']])->find();
            $result[$k]['is_follow'] =$follow?true:false;
            if ($v['juli'] < 1000) {
                $result[$k]['juli'] = $v['juli'].'米';
            } else {
                $distance = $v['juli'] / 1000;
                $result[$k]['juli'] = round($distance, 2).'公里';
            }
        }
        $this->ajaxReturn($result);
    }
    //
    public function isFriend () {
        $add_openid = I('openid');
        $from_openid = I('myopenid');
        $where['wid'] = session('wid');
        $where['add_openid'] = $add_openid;
        $where['from_openid'] = $from_openid;
        $row = M('quan_addfriend')->where($where)->find();
        if ($row) {
            $row['state'] ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        }
        $this->ajaxReturn(0);
    }

    public function changeFriend () {
        $an_openid = I('openid');
        $from_openid = I('myopenid');
        $where['wid'] = session('wid');
        $where['add_openid'] = $an_openid;
        $where['from_openid'] = $from_openid;
        $state = I('state');
        $row = M('quan_addfriend')->where($where)->find();
        if ($row) {
            $suc = M('quan_addfriend')->where($where)->save(['state' => $state]);
            $suc ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        } else {
            $suc = M('quan_addfriend')->add(['state' => $state, 'add_openid' => $an_openid, 'from_openid' => $from_openid, 'wid' => session('wid')]);
            $suc ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        }
    }

    public function addVisit () {
        $data['wid'] = session('wid');
        $data['openid'] = I('openid');
        $data['from_openid'] = I('myopenid');
        if (I('myopenid') != I('openid')) {
            $suc = M('quan_visit_log')->add($data);
        }
        //访问量
        $where['wid'] = session('wid');
        $where['openid'] = I('openid');
        $num = M('quan_visit_log')->where($where)->count();
        $this->ajaxReturn($num);
    }

    //访问日志
    public function getVisitLog () {
        $where['a.wid'] = session('wid');
        $where['a.openid'] = I('openid');
        $list = M('quan_visit_log')->alias('a')
            ->field('b.nickname, b.headimgurl, b.user_age, b.gender, a.last_time, b.openid')
            ->join('tp_member b on a.from_openid = b.openid')
            ->where($where)
            ->order('a.last_time desc')
            ->limit('0, 50')
            ->select();
        $this->ajaxReturn($list);
    }

    //关注
    public function getFollowLog () {
        $where['a.follow_openid'] = I('openid');
        $list = M('quan_follow')->alias('a')
            ->field('b.nickname, b.headimgurl, b.user_age, b.gender, a.last_time, b.openid')
            ->join('tp_member b on a.openid = b.openid')
            ->where($where)
            ->order('a.last_time desc')
            ->limit('0, 50')
            ->select();
        $this->ajaxReturn($list);
    }

    //暗恋
    public function getAnlianLog () {
        $where['a.wid'] = session('wid');
        $where['a.an_openid'] = I('openid');
        $where['a.state'] = 1;
        $list = M('quan_anlian')->alias('a')
            ->field('b.nickname, b.headimgurl, b.user_age, b.gender, a.last_time, b.openid')
            ->join('tp_member b on a.from_openid = b.openid')
            ->where($where)
            ->order('a.last_time desc')
            ->limit('0, 50')
            ->select();
        $this->ajaxReturn($list);
    }

    //举报
    public function reportMember () {
        $data['wid'] = session('wid');
        $data['content'] = $_POST['content'];
        $data['openid'] = $_POST['openid'];
        $data['from_openid'] = $_POST['from_openid'];
        $suc = M('quan_report_log')->add($data);
        $suc ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
    }

    //送礼
    public function getGiftLog () {
        $where['a.wid'] = session('wid');
        $where['a.to'] = I('openid');
        $where['a.is_pay'] = 1;
        $list = M('quan_gift_order')->alias('a')
            ->field('b.nickname, b.headimgurl, b.user_age, b.gender, a.last_time, b.openid')
            ->join('tp_member b on a.from = b.openid')
            ->where($where)
            ->order('a.last_time desc')
            ->limit('0, 50')
            ->select();
        $this->ajaxReturn($list);
    }
    //交友好友列表
    public function getFriendList(){
        $tab = $_POST['tab'];
        $page = $_POST['page'];
        $map = array();
        if($tab == 1){
            $map['gender'] = 0;
        }else if($tab == 2){
            $map['gender'] = 1;
        }
        $map['wid'] = session('wid');
        $map['headimgurl'] = array('neq','');
        $list = M('member')
            ->field("mid,nickname,headimgurl,visit_num,gender,openid,user_height,user_age")
            ->where($map)
            ->order('visit_num DESC')
            ->limit($page*10,10)
            ->select();
        foreach($list as $key=>$value){
            if(empty($value['user_height'])){
                if($value['gender'] == 0){
                    $list[$key]['user_height'] = 160;
                }else{
                    $list[$key]['user_height'] = 170;
                }
            }
            if(empty($value['user_age'])){
                $list[$key]['user_age'] = 18;
            }
        }
        $this->ajaxReturn($list);
    }
    public function chatList(){
        $list = array();
        $map = array();
        $map['wid'] = session('wid');
        $map['send_openid'] = $_POST['openid'];
        $list1 = M('chat_record')->where($map)->group('receive_openid')->select();
        foreach($list1 as $key=>$value){
            $info1 = M('chat_record')
                ->where(array('wid'=>session('wid'),'send_openid'=>$_POST['openid'],'receive_openid'=>$value['receive_openid']))
                ->order('create_time DESC')
                ->field('content,create_time')
                ->find();
            $member1 = M('member')
                ->where(array('wid'=>session('wid'),'openid'=>$value['receive_openid']))
                ->field('nickname,headimgurl')
                ->find();
            $list1[$key]['content'] = $info1['content'];
            $list1[$key]['create_time'] = $info1['create_time'];
            $list1[$key]['nickname'] = $member1['nickname'];
            $list1[$key]['headimgurl'] = $member1['headimgurl'];
            $list1[$key]['openid'] = $value['receive_openid'];
            $list1[$key]['sum'] = 0;
        }
        foreach($list1 as $k1=>$v1){
            array_push($list,$v1);
        }
        $map1 = array();
        $map1['wid'] = session('wid');
        $map1['receive_openid'] = $_POST['openid'];
        $list2 = M('chat_record')->where($map1)->group('send_openid')->select();
        foreach($list2 as $k=>$v){
            $info2 = M('chat_record')
                ->where(array('wid'=>session('wid'),'send_openid'=>$v['send_openid'],'receive_openid'=>$_POST['openid']))
                ->order('create_time DESC')
                ->field('content,create_time')
                ->find();
            $sum = M('chat_record')
                ->where(array('wid'=>2,'send_openid'=>$v['send_openid'],'receive_openid'=>$_POST['openid'],'status'=>1))
                ->count('*');
            if($sum <= 0){
                $sum = 0;
            }
            $member2 = M('member')
                ->where(array('wid'=>session('wid'),'openid'=>$v['send_openid']))
                ->field('nickname,headimgurl')
                ->find();
            $list2[$k]['content'] = $info2['content'];
            $list2[$k]['create_time'] = $info2['create_time'];
            $list2[$k]['nickname'] = $member2['nickname'];
            $list2[$k]['headimgurl'] = $member2['headimgurl'];
            $list2[$k]['openid'] = $v['send_openid'];
            $list2[$k]['sum'] = $sum;
        }
        foreach($list2 as $k2=>$v2){
            array_push($list,$v2);
        }
        $list = $this->array_unset_tt($list,'openid');
        $flag = array();
        foreach($list as $vo){
            $flag[] = $vo['create_time'];
        }
        array_multisort($flag, SORT_DESC, $list);
        $this->ajaxReturn($list);
    }
    function array_unset_tt($arr,$key){
        //建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
            //查看有没有重复项
            if(isset($res[$value[$key]])){
                //有：销毁
                if($value['sum'] > $res[$value[$key]]['sum']){
                    $res[$value[$key]]['sum'] = $value['sum'];
                }
                unset($value[$key]);

            }
            else{

                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }
    public function send(){
        $data = array();
        $data['wid'] = session('wid');
        $data['send_openid'] = $_POST['myopenid'];
        $data['receive_openid'] = $_POST['openid'];
        $data['content'] = $_POST['text'];
        $data['status'] = 1;
        $data['create_time'] = date("Y-m-d H:i:s",time());
        M('chat_record')->add($data);
        $this->ajaxReturn($data);
    }
    public function  chatRecord(){
        $list = array();
        $openid = $_POST['openid'];
        $myopenid = $_POST['myopenid'];
        $page = $_POST['page'];
        $map = array();
        $map['wid'] = session('wid');
        $map['send_openid'] = $openid;
        $map['receive_openid'] = $myopenid;
        $list1 = M('chat_record')->where($map)->select();
        if(!empty($list1)){
            foreach($list1 as $key=>$value){
                array_push($list,$value);
            }
        }

        $map1 = array();
        $map1['wid'] = session('wid');
        $map1['send_openid'] = $myopenid;
        $map1['receive_openid'] = $openid;
        $list2 = M('chat_record')->where($map1)->select();

        if(!empty($list2)){
            foreach($list2 as $k=>$v){
                array_push($list,$v);
            }
        }
        $flag = array();

        foreach($list as $v){
            $flag[] = $v['create_time'];
        }

        array_multisort($flag, SORT_ASC, $list);
        $length = count($list) - $page*7 -1;
        if($length <= 0){
            $length = 0;
        }
        $list = array_slice($list,$length);
        $this->ajaxReturn($list);
    }
    public function setChatStatus(){
        $map = array();
        $map['wid'] = session('wid');
        $map['receive_openid'] = $_POST['myopenid'];
        $map['send_openid'] = $_POST['openid'];
        $data = array();
        $data['status'] = 2;
        M('chat_record')->where($map)->save($data);
    }
    public function unReadNum(){
        $map = array();
        $map['wid'] = session('wid');
        $map['receive_openid'] = $_POST['openid'];
        $map['status'] = 1;
        $count = M('chat_record')->where($map)->count('*');
        if(empty($count)){
            $count = 0;
        }
        $this->ajaxReturn($count);
    }

    //发帖付费数据
    public function getAddTiePayInfo () {
        $openid = I('openid');
        $return = [];
        //发帖价格
        $wechat_p = M('wechat')->where(['wid' => session('wid')])->find();
        $return['quan_wechat'] = $wechat_p['tongcheng_fee'];
        //同城卡
        $tc_card = M('card_log')->alias('a')
                                ->field('a.*, b.is_fee, b.is_num')
                                ->join('tp_card b on a.cid = b.id')
                                ->where(['a.wid' => session('wid'), 'a.openid' => $openid, 'a.end_time' => ['GT', date('Y-m-d H:i:s', time())], 'a.is_pay' => 1])
                                ->order('a.id desc')
                                ->select();
        $return['tc_info'] = $tc_card[0];

        $this->ajaxReturn($return);
    }
    //
    public function releaseInfoPay () {
        $openid = $_POST['openid'];
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        //计算$fee
        //同城卡
        $tc_card = M('card_log')->alias('a')
                                ->field('a.*, b.is_fee, b.is_num')
                                ->join('tp_card b on a.cid = b.id')
                                ->where(['a.wid' => session('wid'), 'a.openid' => $openid, 'a.end_time' => ['GT', date('Y-m-d H:i:s', time())], 'a.is_pay' => 1])
                                ->order('a.id desc')
                                ->select();
        $wechat_p = M('wechat')->where(['wid' => session('wid')])->find();
        $fee_num = $wechat_p['tongcheng_fee'];
        if ($tc_card[0]) {
            //优惠方式
            if ($tc_card[0]['is_fee']) {
                // 1.价格

            } elseif ($tc_card[0]['is_num']) {
                // 2.包条

            } else {
                //都不是
                $fee = $fee_num;
            }


        } else {
            //原价收费
            $fee = $fee_num;
        }

        //插入到tp_quan_order
        $data['wid'] = session('wid');
        $data['openid'] = $openid;
        $data['out_trade_no'] = $this->build_order_no();
//        $data['transaction_id'] = '????????????';
        $data['is_pay'] = 0;
        $data['create_time'] = date('Y-m-d H:i:s', time());
//        $data['type'] = '?????????????';
//        $data['qid'] = '?????????????';
        $data['price'] = $fee;
//        if(!M("quan_order")->add($data)){
//            $arr = array("err_code"=>400,"err_msg"=>"2网络忙，请稍后再试！");
//            $this->ajaxReturn($arr);
//        }

        $url = "https://" . $_SERVER['HTTP_HOST'] . U("Notify/openCard");
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();

        $data['remark'] = "智联同城";// ??

        $input->SetBody($data['remark']);
        $input->SetAttach('同城圈发布');
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($fee * 100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try {
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        } catch (Exception $e) {
            $arr = array("err_code" => 400, "err_msg" => $e->getMessage() . $data['pay_money']);
            $this->ajaxReturn($arr);
        }
        if ($wxorder['return_code'] == "FAIL") {
            $arr = array("err_code" => 400, "err_msg" => $wxorder['return_msg'] . $data['pay_money']);
            $this->ajaxReturn($arr);
        }
        try {
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        } catch (Exception $e) {
            $arr = array("err_code" => 400, "err_msg" => $e->getMessage());
            $this->ajaxReturn($arr);
        }
        echo $jsApiParameters;
    }
}